package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.entity.vo.UcenterMember;
import com.atguigu.eduservice.service.EduCommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2021-08-15
 */
@Api(description = "评论")
@RestController
@RequestMapping("/eduservice/comment")
@CrossOrigin
public class EduCommentController {

    @Autowired
    private EduCommentService commentService;

    @ApiOperation(value = "分页查找评论")
    @PostMapping("getCommentInfo/{page}/{limit}")
    public R getCommentInfo(@PathVariable long page, @PathVariable long limit, @PathVariable String courseId) {

        Page<EduComment> commentPage = new Page<>(page,limit);
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        commentService.page(commentPage,wrapper);

        List<EduComment> items = commentPage.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("items",items);
        map.put("current",commentPage.getCurrent());
        map.put("pages",commentPage.getPages());
        map.put("size",commentPage.getSize());
        map.put("total",commentPage.getTotal());
        map.put("hasNext",commentPage.hasNext());
        map.put("hasPrevious",commentPage.hasPrevious());

        return R.ok().data("map",map);

    }

    @ApiOperation(value = "添加评论")
    @PostMapping("auth/save")
    public R addCommentInfo(@RequestBody EduComment comment,HttpServletRequest request) {

        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)) {
            return R.error().message("请先登录");
        }

        comment.setMemberId(memberId);
        UcenterMember ucenter = commentService.getUcenterInfo(memberId);
        System.out.println(ucenter==null);
        comment.setAvatar(ucenter.getAvatar());
        comment.setNickname(ucenter.getNickname());
        commentService.save(comment);

        return R.ok().data("id",comment.getId());

    }

}

